
var express = require('express');
var router = express.Router();

var UserEntity = require('../models/User').UserEntity;
var RestResult = require('../RestResult');

/* GET users listing. */
router.post('/', function(req, res, next) {
  res.send('user with a resource');
});

router.post('/register', function(req, res, next) {

    var mobile = req.body.mobile;
    var password = req.body.password;
    var restResult = new RestResult();

    console.log(req.body);

    //
    // if (!/1\d{10}/.test(mobile)){//手机号码格式校验
    //     restResult.errorCode = RestResult.ILLEGAL_ARGUMENT_ERROR_CODE;
    //     restResult.errorReason = "请填写真确的手机格式";
    //     res.send(restResult);
    //     return;
    // }
    //
    // if(!password || password.length < 6){//密码长度校验
    //     restResult.errorCode = RestResult.ILLEGAL_ARGUMENT_ERROR_CODE;
    //     restResult.errorReason = "密码长度不能少于6位";
    //     res.send(restResult);
    //     return;
    // }

    UserEntity.findOne({mobile:mobile},'_id',function(err,user){
        if(err){//查询异常
            restResult.errorCode = RestResult.SERVER_EXCEPTION_ERROR_CODE;
            restResult.errorReason = "服务器异常";
            res.send(restResult);
            return;
        }

        if (user){//手机号已注册
            restResult.errorCode = RestResult.BUSINESS_ERROR_CODE;
            restResult.errorReason = "手机号已注册";
            res.send(restResult);
            return;
        }

        var registerUser = new UserEntity({mobile:mobile, password:password});
        //调用实体的实例的保存方法
        registerUser.save(function(err,row){
            if(err){//服务器保存异常
                restResult.errorCode = RestResult.SERVER_EXCEPTION_ERROR_CODE;
                restResult.errorReason = "服务器异常";
                res.send(restResult);
                return;
            }
            res.send(restResult);//返回成功结果
        });

    });
});


router.post('/login', function(req, res, next) {
    res.send('login');
});


module.exports = router;
